﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 240;


    private Rigidbody2D rb;
    private SpriteRenderer sr;
    private PlayerAttack playerAttack;

    private float x, y;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();

        Transform slashTransform = transform.GetChild(0);
        playerAttack = slashTransform.GetComponent<PlayerAttack>();
    }

    private void Update()
    {
        x = Input.GetAxis("Horizontal");
        y = Input.GetAxis("Vertical");

        Flip();
        Attack();
    }


    void FixedUpdate()
    {
        rb.velocity = new Vector2(x * speed * Time.fixedDeltaTime, y * speed * Time.fixedDeltaTime);
    }

    void Flip()
    {
        // 根据鼠标位置修改角色朝向
        float mousePositionX = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
        if (transform.position.x < mousePositionX)
        {
            sr.flipX = false;
        } 
        else if(transform.position.x > mousePositionX)
        {
            sr.flipX = true;
        }
    }
    
    void Attack()
    {
        if (Input.GetMouseButtonDown(0))
        {
            playerAttack.Attack();
        }
    }
}
